# TTL串口接口模块 - 提供TTL串口通信接口

from driver import UART
import ujson as json
import config
import mod_dispatch

# 全局TTL UART对象
ttl_uart = None
TTL_STATUS = True  # 启用TTL功能
module_status = "STOPPED"

def init():
    """初始化TTL模块"""
    global module_status
    print("[TTL] Initializing TTL module...")
    
    if init_ttl():
        module_status = "READY"
        print("[TTL] TTL module initialized successfully")
        return True
    else:
        module_status = "ERROR"
        print("[TTL] TTL module initialization failed")
        return False

def start():
    """启动TTL模块"""
    global module_status
    
    if module_status == "READY":
        module_status = "RUNNING"
        print("[TTL] TTL module started successfully")
        return True
    else:
        print("[TTL] TTL module not ready, cannot start")
        return False

def init_ttl():
    # 初始化TTL UART
    global ttl_uart, TTL_STATUS
    
    if not TTL_STATUS:
        print("[TTL] TTL功能已禁用")
        return False
    
    try:
        ttl_uart = UART()
        ttl_uart.open("TTL")
        print("[TTL] TTL UART initialized successfully")
        return True
    except Exception as e:
        print("[TTL] Failed to initialize TTL UART: {}".format(e))
        return False

def cleanup_ttl():
    # 清理TTL UART资源
    global ttl_uart
    
    try:
        if ttl_uart:
            ttl_uart.close()
            print("[TTL] TTL UART cleaned up successfully")
    except Exception as e:
        print("[TTL] Error during TTL UART cleanup: {}".format(e))

def process_config_command(command_data):
    """处理配置命令 - 通过dispatch统一处理"""
    try:
        # 直接使用dispatch的指令格式，无需映射
        return mod_dispatch.handle_action_for_ttl(command_data)
    
    except Exception as e:
        return {"status": "error", "message": "Command processing error: {}".format(str(e))}




# 配置处理函数已移至统一的config.py接口，不再需要本地处理函数


def send_device_status():
    """发送设备状态信息"""
    try:
        status_info = {
            "system": "HaaS506 DTU",
            "device_sn": config.get_device_sn() or "unknown",
            "config_ready": True,
            "commands_help": "Send JSON commands like: {\"action\":\"get\",\"key\":\"device_sn\"}"
        }
        
        # 通过TTL发送状态
        if ttl_uart:
            status_str = json.dumps(status_info) + '\r\n'
            ttl_uart.write(status_str.encode('utf-8'))
            print("[TTL] Device status sent: {}".format(status_info))
            return True
        else:
            print("[TTL] TTL UART not available")
            return False
            
    except Exception as e:
        print("[TTL] Error sending device status: {}".format(e))
        return False


def process_command():
    # 处理TTL串口接收到的命令
    global ttl_uart
    
    if not ttl_uart:
        return False
    
    try:
        # 检查是否有数据
        if ttl_uart.any() <= 0:
            return False
        
        # 读取命令
        command_buf = bytearray(256)
        bytes_received = ttl_uart.read(command_buf)
        
        if bytes_received <= 0:
            return False
        
        # 解析命令（假设是JSON格式）
        command_str = command_buf[:bytes_received].decode('utf-8').strip()
        print("[TTL] Received command: {}".format(command_str))
        
        try:
            command_data = json.loads(command_str)
            response = process_config_command(command_data)
            
            # 发送响应
            response_str = json.dumps(response) + '\r\n'
            ttl_uart.write(response_str.encode('utf-8'))
            print("[TTL] Response sent: {}".format(response))
            
        except Exception as parse_e:
            # 发送错误响应
            error_response = {"status": "error", "message": "Invalid JSON: {}".format(str(parse_e))}
            response_str = json.dumps(error_response) + '\r\n'
            ttl_uart.write(response_str.encode('utf-8'))
            print("[TTL] Error response sent: {}".format(error_response))
        
        return True
        
    except Exception as e:
        print("[TTL] Error processing command: {}".format(e))
        return False

def get_ttl_status():
    """获取TTL接口状态"""
    global ttl_uart, TTL_STATUS, module_status
    return {
        "ttl_enabled": TTL_STATUS,
        "module_status": module_status,
        "uart_ready": ttl_uart is not None
    }

def send_status():
    """通过TTL发送系统状态信息"""
    return send_device_status()
